package com.example.dell.fastshopping.DuoBao;

import android.arch.lifecycle.Observer;
import android.arch.lifecycle.ViewModelProviders;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import com.example.dell.fastshopping.DuoBao.entity.PriductInfo;
import com.example.dell.fastshopping.DuoBao.entity.RoundResult;
import com.example.dell.fastshopping.DuoBao.model.DuoBaoActViewModel;
import com.example.dell.fastshopping.MyApplication;
import com.example.dell.fastshopping.R;
import com.example.dell.fastshopping.mall.entity.ServerTime;
import com.example.dell.fastshopping.network.http.BaseResponse;
import com.example.dell.fastshopping.user.entity.IntegralBaseInformation;
import com.example.dell.fastshopping.utils.KLog;
import com.example.dell.fastshopping.utils.ToastUtils;
import com.example.dell.fastshopping.views.NumberView;
import com.example.dell.fastshopping.views.RollView;
import com.example.dell.fastshopping.views.SwipeCaptchaView;
import com.youth.banner.Banner;

import java.lang.ref.WeakReference;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by ${YSH} on 2019/4/12.
 * 描述        ${TODO}
 * <p>
 * 更新者       $author$
 * 更新时间     $Data$
 * 描述         ${TODO}
 */
public class DuoBaoActActivity extends AppCompatActivity implements View.OnClickListener {
    @BindView(R.id.banner)
    Banner banner;
    @BindView(R.id.name)
    TextView name;
    @BindView(R.id.lun)
    TextView lun;
    @BindView(R.id.h)
    TextView hour;
    @BindView(R.id.m)
    TextView min;
    @BindView(R.id.s)
    TextView second;
    @BindView(R.id.tab)
    TabLayout tab;
    @BindView(R.id.vp)
    ViewPager vp;
    @BindView(R.id.my_give_money)
    TextView my_give_money;

    @BindView(R.id.last_time)
    TextView lastTime;
    @BindView(R.id.cover)
    RelativeLayout cover;
    @BindView(R.id.swipeCaptchaView)
    SwipeCaptchaView swipeCaptchaView;
    @BindView(R.id.dragBar)
    SeekBar dragBar;
    @BindView(R.id.swipe_container)
    RelativeLayout swipeContainer;

    @BindView(R.id.status)
    TextView status;
    @BindView(R.id.currentStartPrice)
    TextView currentStartPrice;
    @BindView(R.id.duobao_action)
    RelativeLayout duobaoAction;
    @BindView(R.id.give_price)
    NumberView give_price;
    @BindView(R.id.close_swipeview)
    TextView close_swipeview;
    @BindView(R.id.success_fanli)
    TextView success_fanli;
    @BindView(R.id.back)
    ImageView back;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.incrementValue)
    TextView increment;

    @BindView(R.id.duobao_con)
    RelativeLayout duobaoCon;

    @BindView(R.id.close_1)
    ImageView close1;
    @BindView(R.id.close_3)
    TextView close_3;
    @BindView(R.id.lun2)
    TextView lun2;
    @BindView(R.id.request_success)
    RelativeLayout requestSuccess;

    @BindView(R.id.status_button)
    TextView statusButton;

    @BindView(R.id.end_lun)
    TextView endLun;
    private DuoBaoActViewModel viewModel;
    private long startRoundTime;//本轮次开始时间
    private long endRoundTime;//本轮次结束时间
    private int currentRoundId;//本轮次id;
    private int auctionClassId;//竞拍场id
    private int currentRound = 1;//当前第几轮
    private ArrayList<Fragment> fragments;
    private int goodId;


    private boolean canCheckResult = false;//每轮结束只校验一次
    private String limitPrice;
    private BigDecimal jifen_denominator;

    /**
     * msg.what 1: 最后10秒倒计时 ；2 ：每轮的倒计时
     */
    private static class myHandler extends Handler {
        private final WeakReference<DuoBaoActActivity> activityWeak;

        public myHandler(DuoBaoActActivity duoBaoActActivity) {
            activityWeak = new WeakReference<>(duoBaoActActivity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            DuoBaoActActivity duoBaoActActivity = activityWeak.get();
            if (duoBaoActActivity == null) {
                return;
            }
            if (msg.what == 2) {
                duoBaoActActivity.receiveDuoBaoTimeMesage();
            }
        }
    }

    private static Handler myHandle;

    private void receiveDuoBaoTimeMesage() {

        long time = startRoundTime - System.currentTimeMillis();
        long toendtime = endRoundTime - System.currentTimeMillis();
        //倒计时设置
        if (time >= 0 && toendtime > 0) {
            String[] timeArray = viewModel.getTimeArray(time);
            hour.setText(timeArray[0]);
            min.setText(timeArray[1]);
            second.setText(timeArray[2]);
            if (time <= 10000 && time > 0) {
                //最后10秒倒计时
                //startCountdown();
                if (cover.getVisibility() != View.VISIBLE) {
                    cover.setVisibility(View.VISIBLE);
                }

                receiveEndLineMessage(timeArray[3]);


            }
        } else if (time <= 0) {
            hour.setText("00");
            min.setText("00");
            second.setText("00");
        }

        if (time < 0 && toendtime > 0) {
            //竞拍时间段
            buttonAnimationStart();
        } else if (toendtime <= 0) {
            //每轮结束时
            checkResult();
            myHandle.removeCallbacksAndMessages(null);
            return;
        }

        Message obtain = Message.obtain();
        obtain.what = 2;
        myHandle.sendMessageDelayed(obtain, 1000);

    }

    private void receiveEndLineMessage(String time) {
        Integer value = Integer.valueOf(time);
        if (value <= 0) {
            cover.setVisibility(View.GONE);
            status.setText("进行中");
            return;
        }
        lastTime.setText(time);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_duobao_act);
        ButterKnife.bind(this);
        initListener();
        initView();
    }

    private void initView() {
        title.setText("竞拍详情");
        auctionClassId = getIntent().getIntExtra("auctionClassId", 0);
        goodId = getIntent().getIntExtra("goodId", 0);
        myHandle = new myHandler(DuoBaoActActivity.this);
        viewModel = ViewModelProviders.of(this).get(DuoBaoActViewModel.class);


        final String[] tabtile = {"商品介绍", "出价记录", "竞拍规则"};
        fragments = new ArrayList<>();
        fragments.add(GoodsIntroduceFragment.newInstance());
        fragments.add(DuoBaoListFragment.newInstance());
        fragments.add(DuoBaoRuleFragment.newInstance());
        tab.setupWithViewPager(vp);
        tab.setTabIndicatorFullWidth(false);
        vp.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {
            @Override
            public Fragment getItem(int i) {
                return fragments.get(i);
            }

            @Override
            public int getCount() {
                return tabtile.length;
            }

            @Nullable
            @Override
            public CharSequence getPageTitle(int position) {
                return tabtile[position];
            }
        });
        KLog.e("initView");
        //初始禁止竞拍
        closeButtonAnimation();
        vp.setCurrentItem(1, true);

        viewModel.getProductInfo(goodId).observe(this, new Observer<PriductInfo>() {
            @Override
            public void onChanged(@Nullable PriductInfo priductInfo) {
                name.setText(priductInfo.getProductName());
                String pic = priductInfo.getPic();
                viewModel.setBanner(banner, pic);
                currentStartPrice.setText(priductInfo.getProductPrice().toString());
                viewModel.getGoodInfo().setValue(priductInfo.getIntroduction());
            }
        });
        checkServerTime();
    }


    private void checkServerTime() {
        //依据竞拍场id和轮次 校验本次竞拍的时间
        viewModel.checkServerTime(auctionClassId).observe(this, new Observer<ServerTime>() {
            @Override
            public void onChanged(@Nullable ServerTime serverTime) {
                status.setText(serverTime.getStatusString());
                String incrementValue = serverTime.getIncrementValueIntString();
                increment.setText(incrementValue);
                give_price.setNumberDiff(Integer.valueOf(serverTime.getIncrementValueIntString()));
                String lunfinalPrice = serverTime.getFinalPriceString();
                String startPrice = serverTime.getStartPriceString();

                int currentRound = serverTime.getCurrentRound();
                DuoBaoActActivity.this.currentRound = serverTime.getCurrentRound();
                String limitPrice = (serverTime.getStatus() != 3) ? startPrice : lunfinalPrice;
                currentStartPrice.setText(limitPrice);
                DuoBaoActActivity.this.limitPrice = limitPrice;
                lun.setText("当前第" + DuoBaoActActivity.this.currentRound + "轮起拍价：￥" + limitPrice);

                give_price.setNumber(serverTime.getInputNumber());
                startRoundTime = serverTime.getStartRoundTime();
                endRoundTime = serverTime.getEndRoundTime();
                long now = System.currentTimeMillis();
                KLog.e(now + "," + startRoundTime + "," + endRoundTime);
                currentRoundId = serverTime.getCurrentRoundId();

                //开始轮询时间 3:已结束
                if (serverTime.getStatus() != 3) {
                    endLun.setText("当前第" + currentRound + "轮，下一轮抢拍即将开启！");
                    startLunEndtime();
                } else {
                    closeButtonAnimation();
                    statusButton.setText("已结束");
                }

                List<ServerTime.DuobaoHistory> list = serverTime.getList();
                viewModel.getHistoryList().setValue(list);
                if (serverTime.getStatus() == 3 && list.size() > 0) {
                    status.setBackgroundResource(R.drawable.jinpai_status_gray);
                    String user = list.size() > 0 ? list.get(0).getUserName() : "";
                    success_fanli.setVisibility(View.VISIBLE);
                    success_fanli.setText(user + "  抢拍成功" + "  返还积分:" + serverTime.getIntegralPrice());
                } else {
                    status.setBackgroundResource(R.drawable.jingpai_stauts);
                }
            }
        });
    }

    /**
     * 发送竞拍请求
     */
    private void doJinPaiAction() {

        Integer number = give_price.getNumber();
        if (number < Double.valueOf(limitPrice)) {
            ToastUtils.showShort("出价不能低于本轮起拍价");
            return;
        }
        viewModel.doJinPaiAction(currentRoundId, auctionClassId, number, currentRound).observe(this, new Observer<BaseResponse>() {
            @Override
            public void onChanged(@Nullable BaseResponse response) {
                if (response.getCode() == 200) {
                    ToastUtils.showShort("提交成功，请等待结果");
                    statusButton.setText("已竞拍");
                    lun2.setText(currentRound + "");
                    requestSuccess.setVisibility(View.VISIBLE);
                    //TODO;暂无好的方法。竞拍后 要求下次进来该轮状态还是已竞拍状态
                    MyApplication.saveData(auctionClassId + "" + goodId + "" + currentRoundId);
                } else {
                    ToastUtils.showShort("网络请求失败，请重新竞拍");
                    buttonAnimationStart();
                }
            }
        });
    }

    //每轮结束请求结果
    private void checkResult() {
        if (!canCheckResult) {
            return;
        }
        canCheckResult = false;
        requestSuccess.setVisibility(View.GONE);

        //移除
        MyApplication.removeData(auctionClassId + "" + goodId + "" + currentRoundId);
        viewModel.getCurrentRoundResult(currentRoundId, currentRound, auctionClassId).observe(this, new Observer<RoundResult>() {
            @Override
            public void onChanged(@Nullable RoundResult roundResult) {
                if (roundResult == null) {
                    KLog.e("checkResult为空");
                    return;
                }
                currentRound = roundResult.getRound();
                currentRoundId = roundResult.getRoundId();
                status.setText(roundResult.getStatusString());
                statusButton.setText("立即竞拍");
                checkServerTime();
            }
        });
    }

    private void initListener() {
        close_swipeview.setOnClickListener(this);
        duobaoAction.setOnClickListener(this);
        back.setOnClickListener(this);
        close1.setOnClickListener(this);
        close_3.setOnClickListener(this);
        dragBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                swipeCaptchaView.setCurrentSwipeValue(progress);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                dragBar.setMax(swipeCaptchaView.getMaxSwipeValue());
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                swipeCaptchaView.matchCaptcha();
            }
        });

        swipeCaptchaView.setOnCaptchaMatchCallback(new SwipeCaptchaView.OnCaptchaMatchCallback() {
            @Override
            public void matchSuccess(SwipeCaptchaView swipeCaptchaView) {
                //Toast.makeText(DuoBaoActActivity.this, "验证成功 发送竞拍请求", Toast.LENGTH_SHORT).show();

                hiddeSwipeView(false);
                dragBar.setProgress(0);
                doJinPaiAction();
            }

            @Override
            public void matchFailed(SwipeCaptchaView swipeCaptchaView) {
                swipeCaptchaView.resetCaptcha();
                dragBar.setProgress(0);
            }
        });

    }


    /**
     * 每轮倒计时开始
     */
    private void startLunEndtime() {
        KLog.e("开始轮询啦");
        myHandle.removeCallbacksAndMessages(null);
        Message message = Message.obtain();
        message.what = 2;
        myHandle.sendMessageDelayed(message, 1000);
    }

    //显示刷新滑动验证码
    private void showSwipCode() {
        if (swipeContainer.getWidth() == 0) {
            swipeContainer.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                @Override
                public void onGlobalLayout() {
                    swipeCaptchaView.createCaptcha();
                    swipeCaptchaView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                }
            });
        } else {
            swipeCaptchaView.createCaptcha();
        }
        swipeContainer.setVisibility(View.VISIBLE);


    }

    //隐藏刷新滑动验证码 b：可否可以继续竞拍
    private void hiddeSwipeView(boolean b) {
        swipeContainer.setVisibility(View.GONE);
        if (!b) {
            return;
        }
        long time = startRoundTime - System.currentTimeMillis();
        long toendtime = endRoundTime - System.currentTimeMillis();
        if (time < 0 && toendtime > 0) {
            //竞拍时间段
            canCheckResult = false;
            buttonAnimationStart();
        }

    }

    private void buttonAnimationStart() {
        //已经设置可点击了，不用重复设置
        if (canCheckResult) {
            KLog.e("重复开启竞拍按钮");
            return;
        }
        KLog.e("开启竞拍按钮");
        canCheckResult = true;
        //该竞拍 该轮 我已经竞拍过了，不能再竞拍
        if (MyApplication.getSaveData().contains(auctionClassId + "" + goodId + "" + currentRoundId)) {
            statusButton.setText("已竞拍");
            return;
        }
        statusButton.setText("立即竞拍");
        duobaoAction.setClickable(true);
        duobaoAction.setBackgroundResource(R.drawable.red_button2);
        KLog.e(duobaoAction.isClickable() + "");
        final Animation animation = new AlphaAnimation(1, 0.5F); // Change alpha from fully visible to invisible
        animation.setDuration(500); // duration - half a second

        animation.setInterpolator(new LinearInterpolator()); // do not alter animation rate

        animation.setRepeatCount(Animation.INFINITE); // Repeat animation infinitely

        animation.setRepeatMode(Animation.REVERSE); // Reverse animation at the end so the button will fade back in

        duobaoAction.startAnimation(animation);
    }

    private void closeButtonAnimation() {

        duobaoAction.clearAnimation();
        duobaoAction.setClickable(false);//在设置点击事件之后，运行
        duobaoAction.setBackgroundResource(R.drawable.gray_buttom);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.close_3:
            case R.id.close_1:
                requestSuccess.setVisibility(View.GONE);
                break;
            case R.id.duobao_action:
                Integer number = give_price.getNumber();
                if (number < Double.valueOf(limitPrice)) {
                    ToastUtils.showShort("出价不能低于本轮起拍价");
                    return;
                }
                closeButtonAnimation();
                my_give_money.setText(number + "");
                showSwipCode();
                break;
            case R.id.close_swipeview:
                hiddeSwipeView(true);
                break;
            case R.id.back:
                finish();
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (myHandle != null) {
            myHandle.removeCallbacksAndMessages(null);
        }
    }
}
